<style>
.af { float: left; background: #fff; border: 1px solid #aaa; margin-right: 2px; margin-bottom: 2px; cursor: pointer; padding: 5px; }
.img { background: #fff; padding: 5px 5px 15px 5px; margin: 0 2px; border: 1px solid #666; display: inline-block; }
.img img { cursor: pointer; }
</style>

<?php 
$_SESSION[TINYMCE_UPLOAD] = 'upload/plugins/' . basename(dirname(__FILE__)) . '/';
if (!file_exists('../' . $_SESSION[TINYMCE_UPLOAD])) {
  Utils::create('../' . $_SESSION[TINYMCE_UPLOAD]);
}
$id = Utils::get_param('id', 0);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_page', NULL, NULL, NULL, NULL, $opts)->d;

$sys_pages = unserialize(SYS_PAGES);
$opts = new stdClass();
$opts->cd = 't.sys_id = :v1';
$opts->cdv = array(':v1' => SYS_ID);
$objs = $orm->get('pb_page', NULL, NULL, NULL, NULL, $opts)->d;

if (count($data) > 0 && in_array($data[0]->id, $sys_pages)) {
  return;
}
?>
<div class="pure-form pure-form-aligned" style="padding: 10px; width: 1100px;">
  <legend>Page</legend>

  <div class="pure-control-group">
    <label>Name</label>
    <input id="title" type="text" class="pure-input-1-2" placeholder="{New Page}" />
  </div>
  
  <div class="pure-control-group">
    <label>Visible</label>
    <input id="avail" onclick="__data[0].is_visible = (this.checked) ? 1 : 0; render_avail();" type="checkbox" checked="checked"/><label id="avail_txt" for="avail" style="text-align: center;">Visible</label>
  </div>
  
  <div class="pure-control-group">
    <label>Parent</label>
    <select id="parent" style="min-width: 250px;"></select>
  </div>
  
  <div class="pure-control-group">
    <label>Icon</label>
    <span id="icon" class="fa fa-fw fa-lg af" style="float: none;">&#xf000;</span>
    <button class="pure-button" onclick="select_icon(event);">Select</button>
  </div>
  
  <div class="pure-control-group">
    <label>顶广告 (950像素宽)<span  id="uploader"></span></label>
    <label style="text-align: left; height: 95px; vertical-align: middle;"><span id="ad">&nbsp;</span></label>
  </div>
  
  <div class="pure-control-group">
    <label>底广告 (950像素宽)<span  id="uploader2"></span></label>
    <label style="text-align: left; height: 95px; vertical-align: middle;"><span id="ad2">&nbsp;</span></label>
  </div>
  
  <div class="pure-control-group">
    <label>Content</label>
    <label><textarea id="tinymce"></textarea></label>
  </div>
  
  <div class="pure-control-group">
    <label>&nbsp;</label>
    <button class="pure-button pure-input-1-2 pure-button-primary" onclick="submit_obj();">Save</button>
  </div>
  
  <div class="pure-control-group expg">
    <label>&nbsp;</label>
    <button id="del_obj" class="pure-button" onclick="delete_obj();">Delete</button>
    <button id="new_obj" class="pure-button" onclick="__data = []; reset(); render();">New Page</button>
  </div>
</div>

<div id="dialog_change" class="pure-form pure-form-aligned"  title="Change Name" style="display: none;">
  <?php $count = 0;for($i = 0, $il = hexdec(197); $i < $il; $i++) { ?>
    <?php 
      if (sprintf('%03x', $i) == '00f' ||
          sprintf('%03x', $i) == '01f' ||
          sprintf('%03x', $i) == '03f' ||
          sprintf('%03x', $i) == '04f' ||
          sprintf('%03x', $i) == '05f' ||
          sprintf('%03x', $i) == '06f' ||
          sprintf('%03x', $i) == '07f' ||
          sprintf('%03x', $i) == '08f' ||
          sprintf('%03x', $i) == '09f' ||
          sprintf('%03x', $i) == '0af' ||
          sprintf('%03x', $i) == '0cf' ||
          sprintf('%03x', $i) == '0df' ||
          sprintf('%03x', $i) == '0ef' ||
          sprintf('%03x', $i) == '0ff' ||
          sprintf('%03x', $i) == '10f' ||
          sprintf('%03x', $i) == '11f' ||
          sprintf('%03x', $i) == '12f' ||
          sprintf('%03x', $i) == '13f' ||
          sprintf('%03x', $i) == '14f' ||
          sprintf('%03x', $i) == '15f' ||
          sprintf('%03x', $i) == '16f' ||
          sprintf('%03x', $i) == '17f' ||
          sprintf('%03x', $i) == '18f' ||
          sprintf('%03x', $i) == '116' ||
          sprintf('%03x', $i) == '117' ||
          sprintf('%03x', $i) == '020' ||
          sprintf('%03x', $i) == '0b3' ||
          sprintf('%03x', $i) == '0b4' ||
          sprintf('%03x', $i) == '0b5' ||
          sprintf('%03x', $i) == '0b6' ||
          sprintf('%03x', $i) == '0b7' ||
          sprintf('%03x', $i) == '0b8' ||
          sprintf('%03x', $i) == '0b9' ||
          sprintf('%03x', $i) == '0ba' ||
          sprintf('%03x', $i) == '0bb' ||
          sprintf('%03x', $i) == '0bc' ||
          sprintf('%03x', $i) == '0bd' ||
          sprintf('%03x', $i) == '0be' ||
          sprintf('%03x', $i) == '0bf') 
        continue;
    ?>
    <span title="&#xf<?php echo sprintf('%03x', $i); ?>;" onclick="change_icon('&#xf<?php echo sprintf('%03x', $i); ?>;');" class="fa fa-fw fa-lg af">&#xf<?php echo sprintf('%03x', $i); ?>;</span>
  <?php }?>
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __sys_pages = JSON.parse('<?php echo addslashes(json_encode($sys_pages)); ?>');
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __session_id = '<?php echo session_id(); ?>';
  var __sys_id = '<?php echo SYS_ID; ?>';
  var __root;
  
  $(function(){
    $('#avail').button();
    reset();
    
    $('#tinymce').val(__data[0].html);
    tinyMCE.init( {
      // General options
      mode: 'exact',
      elements: 'tinymce',
      theme: 'advanced',
      height: 500,
      width: 700,

      plugins: 'pdw,filebrowser,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist',
      // Theme options
      theme_advanced_buttons1: 'pdw_toggle,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,forecolor,backcolor,|,image,media,|,code,preview,|,fullscreen',
      theme_advanced_buttons2: 'search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,help,|,insertdate,inserttime',
      theme_advanced_buttons3: 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,advhr,|,print,|,ltr,rtl',
      theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
      theme_advanced_toolbar_location: 'top',
      theme_advanced_toolbar_align: 'left',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing: true,

      file_browser_callback: 'filebrowser',
      pdw_toggle_on: '1',
      pdw_toggle_toolbars: '2,3,4',

      theme_advanced_resizing: true,
      theme_advanced_resize_horizontal: false,
      
      // Example content CSS (should be your site CSS)
      theme_advanced_font_sizes: '10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px',
    });

    Upload.init(
      'uploader', 
      __requrl + 'upload_icon', 
      function(rslt, srv_err) {
        __data[0].ad_top = rslt[0].ad_top;
        render_file();
      }, 
      {
        file_queue_limit: 1,
        file_size_limit: '2MB',
        upload_start_handler: function(file) {
          this.setPostParams({
            PHPSESSID: __session_id,
            id: __data[0].id,
            file: __data[0].ad_top,
            attr: 'ad_top'
          });
        },
        debug: 0
      }
    );

    Upload.init(
      'uploader2', 
      __requrl + 'upload_icon', 
      function(rslt, srv_err) {
        __data[0].ad_bottom = rslt[0].ad_bottom;
        render_file();
      }, 
      {
        file_queue_limit: 1,
        file_size_limit: '2MB',
        upload_start_handler: function(file) {
          this.setPostParams({
            PHPSESSID: __session_id,
            id: __data[0].id,
            file: __data[0].ad_bottom,
            attr: 'ad_bottom'
          });
        },
        debug: 0
      }
    );
    
    render();
  });

  function reset() {
    __objs = __objs.sort(function(a, b) {
      return parseFloat(a.order, 10) > parseFloat(b.order, 10) ? 1 : -1;
    });
    __root = Utils.get_root(__objs);
    if (__data.length == 0) {
      __data[0] = {
        id: 0,
        name: '',
        sys_id: __sys_id,
        parent_id: 0,
        is_default: 0,
        is_visible: 1,
        html: '',
        js: '',
        css: '',
        ad_top: '',
        ad_bottom: '',
        icon: ''
      }
    }
  };

  function __set_pages(node, elm) {
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      elm.append('<li value="' + itm.id +'">' +
                    '<a ' + ((__sys_pages.indexOf(parseInt(itm.id, 10)) != -1) ? 'style="pointer-events: none; color: #aaa;"' : '') + 'href="#"' + ((__data.length > 0 && __data[0].id == itm.id) ? ' class="jstree-clicked"' : '') + '>' + itm.name + '</a>' +
                    ((itm.__c.length > 0) ? '<ul id="pgul_' + itm.id + '"></ul>' : '') + 
                 '</li>');
      if (itm.__c.length > 0) {
        __set_pages(itm, $('#pgul_' + itm.id));
      }
    }
  }

  function render() {
    $("#cs_leftbar_objs").empty();
    $("#cs_leftbar_objs").append('<h3 style="padding-left: 10px;">Pages</h3>');
    $("#cs_leftbar_objs").append('<div id="pgul_wrapper" style="padding: 10px 5px; background: #F5F5F5;"></div>');
    $('#pgul_wrapper').append('<ul id="pgul_' + __root.id + '"></ul>');
    __set_pages(__root, $('#pgul_' + __root.id));
    $("#pgul_wrapper")
    .jstree({ "plugins" : ["themes", "html_data", "ui"] })
    .on('loaded.jstree', function() {
      $("#pgul_wrapper").jstree('open_all');
    })
    .bind("select_node.jstree", function (event, data) { 
      var req = {
        id: data.rslt.obj.attr("value")
      };
      Ajax.request(
        __requrl + 'get_obj',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          __data = rslt;
          render_data();
        },
        null
      );
    })
    .delegate("a", "click", function (event, data) { event.preventDefault(); });
    render_data();
  };
  
  function render_data() {
    Url.insert_param('id', __data[0].id);

    $('#icon').html(__data[0].icon);
    render_avail();
    $('#parent').empty();
    render_parent(__root, '');
    $('#parent').val(__data[0].parent_id);
    $('#title').val(__data[0].name);
    
    if (tinyMCE.get('tinymce')) {
      tinyMCE.get('tinymce').setContent(__data[0].html ? __data[0].html : '');
    } else {
      $('#tinymce').val(__data[0].html);
    }
    
    if (__data[0].id != 0) {
      $('#del_obj').show();
      $('#new_obj').show();
    } else {
      $('#del_obj').hide();
      $('#new_obj').hide();
    }
    render_file();
  };

  function render_file() {
    $('#ad').empty();
    $('#ad2').empty();
    
    if (__data[0].ad_top != '') {
      $('#ad').append(
          '<table cellpadding=0 cellspacing=0 class="img">' +
            '<tr><td style="text-align: right;"><i class="fa fa-times" onclick="delete_file(\'ad_top\');"></i></td></tr>' +
            '<tr><td><a rel="prettyPhoto[gallery1]" href="' + __data[0].ad_top + '"><img style="height: 40px;" src="' + __data[0].ad_top + '"></img></a></td></tr>' +
          '</table>');
    }
    
    if (__data[0].ad_bottom != '') {
      $('#ad2').append(
          '<table cellpadding=0 cellspacing=0 class="img">' +
            '<tr><td style="text-align: right;"><i class="fa fa-times" onclick="delete_file(\'ad_bottom\');"></i></td></tr>' +
            '<tr><td><a rel="prettyPhoto[gallery1]" href="' + __data[0].ad_bottom + '"><img style="height: 40px;" src="' + __data[0].ad_bottom + '"></img></a></td></tr>' +
          '</table>');
    }
    
    $("a[rel^='prettyPhoto']").prettyPhoto({
      social_tools: ''
    });
  };

  function render_avail() {
    if (__data[0].is_visible == 1) {
      $('#avail')[0].checked = true;
      $('#avail_txt').empty();
      $('#avail_txt').append('<span class="ui-button-text">Visible</span>');
      $('#avail_txt').addClass('ui-state-active');
    } else {
      $('#avail')[0].checked = false;
      $('#avail_txt').empty();
      $('#avail_txt').append('<span class="ui-button-text">Invisible</span>');
      $('#avail_txt').removeClass('ui-state-active');
    }
  };

  function render_parent(node, prefix) {
    $('#parent').append('<option value="' + node.id + '"' + ((node.id == __data[0].id) ? ' disabled="disabled"' : '') + '>' + ((prefix == '') ? '' : prefix + ') ') + node.name +'</option>');
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      render_parent(itm, ((prefix == '') ? '(' : '\u2002' + prefix + '-') + (parseInt(idx, 10) + 1));
    }
  };

  function submit_obj() {
    req = __data[0];
    req.name = $('#title').val();
    req.html = tinyMCE.get('tinymce').getContent();
    req.parent_id = $("#parent option:selected").val();
    req.icon = $('#icon').html();

    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        if (rslt.__objs) {
          __objs = rslt.__objs;
          delete rslt.__objs;
        }
        __data[0] = rslt;
        reset();
        render();
      },
      null
    );
  };
  
  function delete_obj() {
    Ajax.request(
      __requrl.replace(__file, 'index') + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(__data[0])),
      function(rslt) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id);
      },
      { confirm: 1 }
    );
  };

  function get_obj(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        render();
      },
      null
    );
    return false;
  };

  function change_icon(val) {
    $('#icon').html(val);
    $('#dialog_change').dialog('close');
  };

  function select_icon(ev) {
    $('#dialog_change').dialog({
      width: 750,
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
    });
  };

  function delete_file(attr) {
    if (__data[0].id != 0) {
      __data[0].__nofile = 1;
      __data[0].__attr = attr;
      submit_obj();
    }
    __data[0][attr] = '';
    render_file();
  };
  /*]]>*/
</script>